/****************************************************************************
 * Copyright (C) 2012 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "CheckForUpdateTask.h"
#include "../../Controls/Application.h"
#include "../../Prompts/PromptWindows.h"
#include "../svnrev.h"
#include "../http.h"

CheckForUpdateTask::CheckForUpdateTask()
{
	running = true;
	rev = 0;
	url = "";
	Prompt = NULL;
	
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void CheckForUpdateTask::CloseProgress()
{
	Prompt->SetEffect(EFFECT_SLIDE_TOP | EFFECT_SLIDE_OUT, 50);
	while(Prompt->IsAnimated())
		usleep(50);
	
	Application::Instance()->PushForDelete(Prompt);
}

void CheckForUpdateTask::TaskError(const char * msg)
{
	ShowError(msg);
	
	rev = 0;
	url = "";
	running = false;
}

void CheckForUpdateTask::Execute(void)
{
	if(!NetworkInitPrompt())
	{
		TaskError(tr("Network is not initiated."));
		running = false;
		return;
	}
	
	Prompt = new ThrobberWindow(tr("Checking for new update"), tr("Please wait..."), tr("Cancel"));
	Prompt->DimBackground(true);
	Application::Instance()->Append(Prompt);
	Application::Instance()->SetUpdateOnly(Prompt);
	
	char *revPtr = 0;
	char *downloadLink = 0;
	char *ptr = 0;
	
	struct block file = downloadfile("http://savegame-manager-gx.googlecode.com/svn/branches/Updates/update.xml");
	if (!file.data)
		goto err;
	
	file.data[file.size-1] = 0;
	
	revPtr = strstr((char*)file.data, "rev=\"");
	if(!revPtr) {
		free(file.data);
		goto err;
	}
	revPtr += strlen("rev=\"");
	
	rev = atoi(revPtr);
	
	if (rev <= GetIntRev()) {
		free(file.data);
		CloseProgress();
		running = false;
		return;
	}
	
	downloadLink = strstr(revPtr, "link=\"");
	if(!downloadLink) {
		free(file.data);
		goto err;
	}
	downloadLink += strlen("link=\"");
	
	ptr = strchr(downloadLink, '"');
	if(!ptr) {
		free(file.data);
		goto err;
	}
	*ptr = 0;
	
	free(file.data);
	url = downloadLink;
	
	sleep(1);
	
	CloseProgress();

	running = false;
	return;
	
  err:
	CloseProgress();
	TaskError(tr("Could not get update infos."));
	running = false;
}
